package com.sunsharing.transport.netty;

import com.sunsharing.common.Context;
import com.sunsharing.common.URL;
import com.sunsharing.transport.Channel;
import com.sunsharing.transport.ConnectClients;
import com.sunsharing.transport.LongChannel;
import com.sunsharing.transport.mina.MinaClient;
import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-4-23
 * Time: 上午12:33
 * To change this template use File | Settings | File Templates.
 */
public class NettyChannel  extends LongChannel {
    Logger logger = Logger.getLogger(NettyChannel.class);

    org.jboss.netty.channel.Channel session;
    public NettyChannel(org.jboss.netty.channel.Channel s,URL url)
    {
        super(url);
        this.session = s;
    }
    @Override
    protected void sendMsg(Context context)
    {
        if(session!=null)
        {
            try
            {
                //logger.error("发送出错:"+url+":::"+context.getHistory().size());
                session.write(context);
            }catch (Exception e)
            {
                logger.error("发送出错:"+url+":::",e);
                throw new RuntimeException("发送出错");
            }
        }
    }

    public void stop()
    {
        super.stop();
        if(session!=null)
        {
            try
            {
                session.close();
            }catch (Exception e)
            {

            }
        }
        session = null;
    }

    public boolean isclose()
    {
        if(this.session ==null)
        {
            return true;
        } else
        {
            return false;
        }
    }

    public void clone(Channel s)
    {
        this.session = ((NettyChannel)s).session;
        this.setUrl(s.url);
    }

    public void reconnect()
    {
        if(this.isClient())
        {
            this.stop();
            try
            {
                //ConnectClients.removeClient(this);
                new NettyClient().connect(url,this.getIoHandle());
            }catch (Exception e)
            {
                logger.error("连接错误",e);
            }
        }
    }

}